package com.mokio.controller;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @program: xiaomishop
 * @ClassName ImageServlet
 * @description:
 * @author: mokio
 * @create: 2025−01-01 19:16
 * @Version 1.0
 **/
@WebServlet("/imageServlet")
public class ImageServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型为图片
        response.setContentType("image/jpeg");

        // 创建验证码图片
        int width = 100, height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 生成随机验证码
        Random random = new Random();
        String code = String.format("%04d", random.nextInt(10000)); // 4位数字验证码
        g.setColor(Color.BLACK);
        g.setFont(new Font("黑体", Font.BOLD, 20));
        g.drawString(code, 20, 20);

        // 将验证码存入 Session
        HttpSession session = request.getSession();
        session.setAttribute("code", code);

        // 输出图片
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }
}
